﻿using Albatross.WPF.Common.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Albatross.SharePoint.Explorer.ViewModels {
	public class ObjectProperty : ViewModel {
		public PropertyInfo Property { get; private set; }

		public const string NamePropertyName = "Name";
		private string _name;
		public string Name {
			get { return _name; }
			set {
				if (_name == value) { return; }
				RaisePropertyChanging(NamePropertyName);
				_name = value;
				RaisePropertyChanged(NamePropertyName);
			}
		}

		public const string ValuePropertyName = "Value";
		private string _value;
		public string Value {
			get { return _value; }
			set {
				if (_value == value) { return; }
				RaisePropertyChanging(ValuePropertyName);
				_value = value;
				RaisePropertyChanged(ValuePropertyName);
			}
		}

		public const string TypePropertyName = "Type";
		private string _type;
		public string Type {
			get { return _type; }
			set {
				if (_type == value) { return; }
				RaisePropertyChanging(TypePropertyName);
				_type = value;
				RaisePropertyChanged(TypePropertyName);
			}
		}

		
		public const string IsValudRetrievedPropertyName = "IsValudRetrieved";
		private bool _isValueRetrieved;
		public bool IsValudRetrieved {
			get { return _isValueRetrieved; }
			set {
				if (_isValueRetrieved == value) { return; }
				RaisePropertyChanging(IsValudRetrievedPropertyName);
				_isValueRetrieved = value;
				RaisePropertyChanged(IsValudRetrievedPropertyName);
			}
		}
		
		public const string IsSelectedPropertyName = "IsSelected";
		private bool _isSelected;
		public bool IsSelected {
			get { return _isSelected; }
			set {
				if (_isSelected == value) { return; }
				RaisePropertyChanging(IsSelectedPropertyName);
				_isSelected = value;
				RaisePropertyChanged(IsSelectedPropertyName);
			}
		}
		
		string GetTypeText(Type type) {
			if (type.IsGenericType) {
				StringBuilder sb = new StringBuilder(type.Name);
				foreach (Type genericType in type.GetGenericArguments()) {
					sb.Append(" ");
					sb.Append(genericType.Name);
				}
				return sb.ToString();
			} else {
				return type.Name;
			}
		}

		public ObjectProperty Set(object obj, PropertyInfo property) {
			Property = property;
			Name = property.Name;
			Type = GetTypeText(property.PropertyType);
			this.Set(obj);
			return this;
		}

		public ObjectProperty Set(object obj) {
			try {
				Value = Convert.ToString(Property.GetValue(obj));
				_isValueRetrieved = true;
			} catch (Exception) {
				Value = "Value Not Retrieved";
				_isValueRetrieved = false;
			}
			return this;
		}
	}
}
